<template>
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>
  <van-divider>已选标签</van-divider>

  <div v-if="activeIds.length === 0">请选择标签</div>
  <van-row gutter="16" style="padding: 0 16px">
    <van-col v-for="tag in activeIds">
      <van-tag  closeable size="small" type="primary" @close="doClose(tag)">
        {{tag}}
      </van-tag>
    </van-col>
  </van-row>


  <van-divider>选择标签</van-divider>

  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <div style="padding: 12px">
    <van-button type="primary" @click="doSearchResult" block>搜索</van-button>
  </div>
</template>

<script setup>

import {showToast} from "vant";
import {ref} from "vue";
import {useRouter} from "vue-router";

const router = useRouter();

const originList = [
  {
    text: '年级',
    children: [
      { text: '大一', id: '大一' },
      { text: '大二', id: '大二' },
      { text: '大三', id: '大三', disabled: true },
    ],
  },
  {
    text: '性别',
    children: [
      { text: '男', id: '男' },
      { text: '女', id: '女' },
      { text: '未知', id: '未知' },
    ],
  },
];

let tagList = ref(originList);

// 搜索内容
const searchText = ref('');
// 点击搜索
const onSearch = (val) => {
  // 把每个children进行一次遍历就行了
  tagList.value = originList.map(parentTag => {
    const tempChildren = [...parentTag.children];
    const tempParentTag = {...parentTag};

    tempParentTag.children = tempChildren.filter(item => item.text.includes(searchText.value));
    return tempParentTag;
  });
};
const onCancel = () => {
  searchText.value = "";
  tagList.value = originList;
};

const show = ref(true);
const close = () => {
  show.value = false;
};

// 已选中的标签
const activeIds = ref([]);
const activeIndex = ref(0);

const doClose = (tag) => {
  //activeIds是一个包装对象，要用value来取它的值
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag
  })
}

/**
 * 当用户点击搜索后跳转页面
 */
const doSearchResult = ()=> {
  router.push({
    path: "/user/list",
    query: {"tags" : activeIds.value}
  })
}

</script>

<style scoped>

</style>